package com.xiaoc.bulldozer.common.service.impl;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.converter.WxPayOrderNotifyResultConverter;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class SafeWxPayServiceImpl extends WxPayServiceImpl {

    @Override
    public WxPayOrderNotifyResult parseOrderNotifyResult(String xmlData) throws WxPayException {
      try {
        log.debug("微信支付异步通知请求参数：{}", xmlData);
        WxPayOrderNotifyResult result = fromXML(xmlData);
        log.debug("微信支付异步通知请求解析后的对象：{}", result);
        result.checkResult(this, null, false);
        return result;
      } catch (WxPayException e) {
        log.error(e.getMessage(), e);
        throw e;
      } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new WxPayException("发生异常，" + e.getMessage(), e);
      }
    }

    public static WxPayOrderNotifyResult fromXML(String xmlString) {
//        XStream xstream = XStreamInitializer.getInstance();
        XStream xstream = new XStream(new DomDriver());

        xstream.processAnnotations(WxPayOrderNotifyResult.class);
        xstream.registerConverter(new WxPayOrderNotifyResultConverter(xstream.getMapper(), xstream.getReflectionProvider()));
        WxPayOrderNotifyResult result = (WxPayOrderNotifyResult) xstream.fromXML(xmlString);
        result.setXmlString(xmlString);
        return result;
      }
}
